﻿namespace ApiLib.Utils;

/// <summary>
/// Utools AI 助手工具类
/// </summary>
public class AiAssistantUtil
{
    public const string Url = "https://ai.u-tools.cn/v1/chat/completions?access_token=";

    #region 刷新token

    private static readonly DateTime DateTimeBase = new DateTime(1970, 1, 1, 0, 0, 0,DateTimeKind.Utc);
    private static long _expiredAt = 0;
    private static string _token="";
    private const string _refreshTokenUrl = "http://192.168.86.106:3000/api/get-access-token";
    private class RefreshTokenResponse
    {
        public string token { get; set; }
        public long expired_at { get; set; }
    }
    private static async Task<string> GetToken()
    {
        if (!string.IsNullOrEmpty(_token) && DateTime.UtcNow<DateTimeBase.AddSeconds(_expiredAt-60))
        {
            return _token;
        }

        var response=await HttpUtil.HttpGetAsync<RefreshTokenResponse>(_refreshTokenUrl);
        if (response!=null)
        {
            _token=response.token;
            _expiredAt=response.expired_at;
            return _token;
        }
        throw new Exception("获取token失败");
    }

    #endregion

    #region 刷新token2
    private static async Task<string> GetToken2()
    {
        var url =
            $"https://open.u-tools.cn/temporary_token?access_token=xiq4kryzgmgn3kjhqwrusgtlixoilk0mektbjy6p&plugin_name=aihub";
        if (!string.IsNullOrEmpty(_token) && DateTime.UtcNow<DateTimeBase.AddSeconds(_expiredAt-60))
        {
            return _token;
        }

        var response=await HttpUtil.HttpGetAsync<RefreshTokenResponse>(url);
        if (response!=null)
        {
            _token=response.token;
            _expiredAt=response.expired_at;
            return _token;
        }
        throw new Exception("获取token失败");
    }

    #endregion

    /// <summary>
    /// 发送消息
    /// </summary>
    /// <param name="content"></param>
    /// <returns></returns>
    public static async Task<AiAssistantResponse?> SendMessage(string content)
    {
        var request = new AiAssistantRequest(content);
        return await SendMessage(request);
    }

    /// <summary>
    /// 发送消息
    /// </summary>
    /// <param name="request"></param>
    /// <returns></returns>
    public static async Task<AiAssistantResponse?> SendMessage(AiAssistantRequest request)
    {
        var token = await GetToken2();
        return await HttpUtil.HttpPostAsync<AiAssistantResponse>(url: Url+token, body: request);
    }
}

public class AiAssistantRequest
{
    /// <summary>
    /// 模型
    /// </summary>
    public string model { get; set; } = "deepseek-r1";

    public List<AiAssistantRequestMessage> messages { get; set; }

    /// <summary>
    /// 是否流式
    /// </summary>
    public bool stream { get; set; } = false;

    public AiAssistantRequest()
    {
    }

    public AiAssistantRequest(string content)
    {
        messages = [new AiAssistantRequestMessage() { content = content }];
    }

    public AiAssistantRequest(string model, string content)
    {
        this.model = model;
        messages = [new AiAssistantRequestMessage() { content = content }];
    }

    public AiAssistantRequest(string model, string role, string content)
    {
        this.model = model;
        messages = [new AiAssistantRequestMessage() { role = role, content = content }];
    }
}

public class AiAssistantRequestMessage
{
    /// <summary>
    /// 角色
    /// </summary>
    public string role { get; set; } = "user";

    /// <summary>
    /// 内容
    /// </summary>
    public string content { get; set; }
}

public class AiAssistantResponse
{
    /// <summary>
    /// id:021742552576566648711242cdb7342d6549650083d9399c53dfe
    /// </summary>
    public string id { get; set; }

    /// <summary>
    /// 模型类型deepseek-r1-distill-qwen-32b-250120
    /// </summary>
    public string model { get; set; }

    /// <summary>
    /// default
    /// </summary>
    public string service_tier { get; set; }

    /// <summary>
    /// chat.completion
    /// </summary>
    public string @object { get; set; }

    /// <summary>
    /// 时间戳
    /// </summary>
    public long created { get; set; }

    public AiAssistantResponseUsage usage { get; set; }
    public List<AiAssistantResponseChoice> choices { get; set; }
}

public class AiAssistantResponseChoice
{
    /// <summary>
    /// stop
    /// </summary>
    public string finish_reason { get; set; }

    public int index { get; set; }
    public object logprobs { get; set; }
    public AiAssistantResponseChoiceMessage message { get; set; }
}

public class AiAssistantResponseChoiceMessage
{
    /// <summary>
    /// 回答
    /// </summary>
    public string content { get; set; }

    /// <summary>
    /// 思考过程
    /// </summary>
    public string reasoning_content { get; set; }

    /// <summary>
    /// 角色：assistant
    /// </summary>
    public string role { get; set; }
}

public class AiAssistantResponseUsage
{
    public int completion_tokens { get; set; }
    public int prompt_tokens { get; set; }
    public int total_tokens { get; set; }
    public AiAssistantResponseUsagePromptTokensDetails prompt_tokens_details { get; set; }
    public AiAssistantResponseUsageCompletionTokensDetails completion_tokens_details { get; set; }
}

public class AiAssistantResponseUsagePromptTokensDetails
{
    public int cached_tokens { get; set; }
}

public class AiAssistantResponseUsageCompletionTokensDetails
{
    public int reasoning_tokens { get; set; }
}